import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  Text,
  FlatList,
  TextInput,
  TouchableOpacity,
  Image,
  KeyboardAvoidingView
} from 'react-native'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import Toast from 'react-native-simple-toast'
import { theme_app, theme_text } from '../../utils/appTheme'
import { isNotEmptyString } from '../../utils/structureJudgment'
import MyTextInput from '../../components/MyTextInput'

import { batchAddSign } from '../../netServer/signs_net'

import Button from "../../components/Button";




class TabelePage extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isCommiting: false,
      updateSeletedStatus: 1,
      tttt: 'asddf',
      isSeletedAll: false
    }
    this.unitOpion = {
      shenggao: ' cm',
      tizhong: ' kg',
      tiwen: ' ℃',
      xinlv: ' 次/分',

      maibo: ' 次/分',
      huxi: ' 次/分',
      dabian: ' 次/日',
      xueya: ' mmHg'
    }

    this.keyOpinion = {
      shenggao: '身高',
      tizhong: '体重',
      tiwen: '体温',
      xinlv: '心率',

      maibo: '脉搏',
      huxi: '呼吸',
      dabian: '大便',
      xueya: '血压'
    }
  }

  //规定类（这个组件）的属性类型，使用时可定义这些属性
  static propTypes = {
    pageStyle: PropTypes.string,
    patientList: PropTypes.array
  }

  _freshSeletedStatus = () => {
    let marr = this.state.updateSeletedStatus + 1
    let isAllSelet = true

    this.props.patientList.forEach(element => {
      if (!element.isSeleted) {
        isAllSelet = false
      }
    })

    this.setState({
      updateSeletedStatus: marr,
      isSeletedAll: isAllSelet
    })
  }

  _controlSeletedStatu = () => {
    this.props.patientList.forEach(element => {
      element.isSeleted = !this.state.isSeletedAll
    })

    this._freshSeletedStatus()
  }

  _commitdata = () => {
    // params.append('taskIds[' + markIndex + ']', element.task_id

    let params = new FormData()

    let { user_id } = this.props.user_info
    params.append('userId', user_id)

    let tempASrr = []
    let markIndex = 0
    for (let index = 0; index < this.props.patientList.length; index++) {
      const element = this.props.patientList[index]
      if (element.isSeleted) {
        let key_opt = this.keyOpinion[this.props.pageStyle]
        if (isNotEmptyString(element.value)) {
          params.append(
            'data[' + markIndex + '][patientNo]',
            element.patient_no
          )
          // params.append(
          //   'data[' + markIndex + ']signData[' + 0 + ']name',
          //   key_opt
          // )
          // params.append(
          //   'data[' + markIndex + ']signData[' + 0 + ']value',
          //   element.value
          // )

          let signData = {
            name: key_opt,
            value: element.value
          }

          params.append(
            'data[' + markIndex + '][signData]',
            JSON.stringify([signData])
          )

          tempASrr.push(element.patient_no)

          markIndex++
        } else {
          Toast.showWithGravity(`请输入疗养员${key_opt}值`, 1, Toast.CENTER)
          return
        }
      }
    }

    if (tempASrr.length < 1) {
      Toast.showWithGravity('您未选择疗养员', 1, Toast.CENTER)
      return
    }
    this.setState({ isCommiting: true });

    batchAddSign(params, resp => {


      this.setState({ isCommiting: false });
      let { code, data, msg } = resp
      if (code == '0') {
        Toast.showWithGravity('数据提交成功！！', 2, Toast.CENTER)
      } else {
        Toast.showWithGravity(msg, 1, Toast.CENTER)
      }
    })
  }

  _renderItem = ({ item }) => {
    let seletIcon = item.isSeleted
      ? require('./src/xuanzhong-2.png')
      : require('./src/xuanzhong.png')
    return (
      <View
        style={{
          width: screenWidth,
          backgroundColor: 'white',
          borderBottomColor: '#efefef',
          borderBottomWidth: 1,
          flexDirection: 'row'
        }}
      >
        <TouchableOpacity
          style={{
            flex: 1,
            width: 50,
            alignItems: 'center',
            justifyContent: 'center'
          }}
          onPress={() => {
            item.isSeleted = !item.isSeleted

            this._freshSeletedStatus()
          }}
        >
          <Image style={{ width: 35, height: 35 }} source={seletIcon} />
        </TouchableOpacity>
        <View
          style={{
            width: 0.6 * (screenWidth - 50),
            padding: 10
          }}
        >
          <Text style={{ paddingTop: 5, paddingBottom: 5 }}>{item.name}</Text>
          <View
            style={{ flexDirection: 'row', justifyContent: 'space-between' }}
          >
            <Text>
              {item.sex == 1 ? '男' : '女'}/{item.age}
            </Text>
            <Text>{item.bed_no} </Text>
          </View>

          <Text style={{ paddingTop: 5, paddingBottom: 5, color: 'green' }}>
            {item.gradeName}
          </Text>

          <Text style={{ color: 'red' }}>{item.allergy}</Text>
        </View>
        <View
          style={{
            width: 0.4 * (screenWidth - 50),
            height: 100,
            alignItems: 'center',
            flexDirection: 'row'
          }}
        >
          <View style={{ flex: 1 }}>
            <TextInput
              style={{
                flex: 1,
                fontSize: 20,
                textAlign: 'right',
                color: '#008800'
              }}
              onChangeText={text => {
                item.value = text
              }}
              defaultValue={item.value}
              keyboardType={
                this.props.pageStyle === 'xueya'
                  ? 'numbers-and-punctuation'
                  : 'numeric'
              }
              underlineColorAndroid="transparent"
              selectionColor="rgb(35,151,246)"
            />
          </View>
          <Text style={{ fontSize: 20, color: '#008800' }}>
            {this.unitOpion[this.props.pageStyle]}
          </Text>
          <Text>&nbsp;&nbsp;&nbsp;&nbsp;</Text>
        </View>
      </View>
    )
  }

  _keyExtractor = (item, index) => item.patient_no

  _separator = () => {
    return <View style={{ height: 1, backgroundColor: '#efefef' }} />
  }

  render() {
    let seletIcon = this.state.isSeletedAll
      ? require('./src/xuanzhong-2.png')
      : require('./src/xuanzhong.png')
    return (
      <KeyboardAvoidingView
        keyboardVerticalOffset={60}
        behavior="padding"
        style={styles.container}
      >
        {/* <View style={styles.container}> */}
        <FlatList
          keyboardShouldPersistTaps="always"
          keyboardDismissMode="on-drag"
          ItemSeparatorComponent={this._separator}
          data={this.props.patientList}
          extraData={this.state.updateSeletedStatus}
          keyExtractor={this._keyExtractor}
          renderItem={this._renderItem}
        />
        <View
          style={{
            width: screenWidth,
            height: 45,
            flexDirection: 'row'
          }}
        >
          <TouchableOpacity
            onPress={this._controlSeletedStatu}
            style={{
              width: 90,
              height: 45,
              alignItems: 'center',
              justifyContent: 'center',
              flexDirection: 'row',
              backgroundColor: 'white'
            }}
          >
            <View style={{ width: 8 }} />
            <Image style={{ width: 34, height: 35 }} source={seletIcon} />
            <View style={{ width: 8 }} />
            <View
              style={{
                backgroundColor: 'white',
                justifyContent: 'center',
                alignItems: 'center'
              }}
            >
              <Text style={{ width: 40 }}>全选</Text>
            </View>
          </TouchableOpacity>

          <Button
            isLoading={this.state.isCommiting}
            isLoadStr="提交中..."
            style={{
              width: screenWidth - 90,
              height: 45,
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: '#1296db'
            }}
            onPress={this._commitdata}
          >
            <Text
              style={{
                fontSize: 18,
                color: "white"
              }}
            >
              提交
                  </Text>
          </Button>

          {/* <TouchableOpacity
            style={{
              width: screenWidth - 90,
              height: 45,
              alignItems: 'center',
              justifyContent: 'center',
              backgroundColor: '#1296db'
            }}
            onPress={this._commitdata}
          >
            <Text style={{ color: 'white', fontSize: 18 }}>提交2</Text>
          </TouchableOpacity> */}
        </View>
        {/* </View> */}
      </KeyboardAvoidingView>
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme_app.bg_color
  }
})

function select(store) {
  return { user_info: store.userInfo.user_info }
}

export default connect(select)(TabelePage)
